﻿#region 信息

// Copyright©2014 Rex Rao all rights reserved.
// File name : SoMcCoffee\Sohobloo.SoCommon\ArgumentHelper.cs
// Author : Sohobloo
// Create time : 2014/02/07 11:17
// Update time : 2014/02/07 17:43

#endregion

#region 引用

using System;
using System.Collections;
using Sohobloo.SoCommon.CommonExtension;

#endregion

namespace Sohobloo.SoCommon
{
    public class ArgumentHelper
    {
        private static ArgumentHelper _instance;

        public static ArgumentHelper Instance
        {
            get
            {
                if(_instance.IsNull())
                {
                    _instance = new ArgumentHelper();
                }
                return _instance;
            }
        }

        private ArgumentHelper()
        {
        }

        public ArgumentHelper CheckNull(object arg, string argName = null)
        {
            if(arg.IsNull())
            {
                throw new ArgumentNullException(argName);
            }
            return _instance;
        }

        public ArgumentHelper CheckEmpty(string arg, string argName = null)
        {
            if(arg.IsNullOrEmpty())
            {
                throw new ArgumentException(
                    string.Format("{0} can not be empty string.", (argName.IsNotNullOrEmpty() ? argName : "Argument")),
                    "argName");
            }
            return _instance;
        }

        public ArgumentHelper CheckRange<T>(T arg, T min, T max, string argName = null) where T:IComparable
        {
            if(arg.CompareTo(min) < 0 || arg.CompareTo(max) > 0)
            {
                throw new ArgumentOutOfRangeException(argName);
            }
            return _instance;
        }


        public ArgumentHelper Check(bool arg, string argName = null)
        {
            if(!arg)
            {
                throw new ArgumentException(string.Format("{0} must be true",
                    (argName.IsNotNullOrEmpty() ? argName : "Argument")));
            }
            return _instance;
        }

        public ArgumentHelper SetNullToEmpty(ref string arg)
        {
            arg = arg.NullToEmpty();
            return _instance;
        }

        public ArgumentHelper SetNullToEmpty<T>(ref T arg) where T : ICollection, new()
        {
            arg = arg.NullToEmpty();
            return _instance;
        }

        public ArgumentHelper SetRange<T>(ref T arg, T min, T max) where T : IComparable
        {
            arg = arg.RestrictBetween(min, max);
            return _instance;
        }

        public ArgumentHelper SetRange<T>(ref T arg, T value, RangeRestriction restrictionType) where T : IComparable
        {
            arg = arg.Restrict(value, restrictionType);
            return _instance;
        }
    }
}